package com.bshinfo.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.bshinfo.web.base.controller.BaseController;
import com.bshinfo.web.service.serviceI.category.CategoryServiceI;

/**
 * 功能描述: 课程分类管理控制层<BR/>
 * 
 * @author [tuxiaokang]
 * 
 * @see [CategoryManageController]
 * 
 * @since [JDK 1.7]
 * 
 * @version [1.0]
 * 
 * @Date [2017-3-1 10:24:28]
 */
@Controller
@RequestMapping("/category")
public class CategoryManageController extends BaseController {
	public static Logger logger = Logger
			.getLogger(CategoryManageController.class);

	@RequestMapping("/categoryManage.bsh")
	public String init(HttpServletRequest request, HttpServletResponse response) {
		return "baseData/systemManage/category/categoryManage.ftl";
	}

	@RequestMapping("/category.bsh")
	public String getInit(HttpServletRequest request,
			HttpServletResponse response) {
		return "baseData/systemManage/category/category.ftl";
	}

	/**
	 * @throws IOException
	 * 
	 * @Title: getAllCategory
	 * @Description:(获取所有的分类，加载分类树)
	 * @param @param request
	 * @param @param response
	 * @param @return    设定文件
	 * @return Object    返回类型
	 */
	@RequestMapping("/getAllCategory.bsh")
	@ResponseBody
	public void getAllCategory(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		List<Map<String, Object>> tree;
		JSONObject json = new JSONObject();
		try {
			tree = categoryServiceI.getAllCategory();
			json.put("tree", tree);
			json.put("status", "success");
			json.put("msg", "获取课程分类信息成功!");
		} catch (Exception e) {
			logger.error("[请求课程分类信息异常!-ErrorMsg:]", e);
			super.exceptionProcessorHandler(request,
					"CategoryManageController", "getAllCategory", "请求课程分类", e);
			json.put("status", "error");
			json.put("msg", "请求课程分类信息异常!");
		}
		response.getWriter().write(json.toString());
	}

	/**
	 * @Title: getUpCategory
	 * @Description:(获取上级分类)
	 * @param @param request
	 * @param @param response
	 * @throws
	 */
	@RequestMapping("/getUpCategory.bsh")
	@ResponseBody
	public void getUpCategory(HttpServletRequest request,
			HttpServletResponse response, String id) {
		List<Map<String, Object>> tree;
		JSONObject json = new JSONObject();
		try {
			tree = categoryServiceI.getUpCategory(id);
			json.put("tree", tree);
			response.getWriter().write(json.toString());
		} catch (Exception e) {
			logger.error("[请求课程分类信息异常!-ErrorMsg:]", e);
		}
	}

	/**
	 * @Title: addCategory
	 * @Description:(新增分类)
	 * @param @param request
	 * @param @param response
	 * @throws
	 */
	@RequestMapping("/addCategory.bsh")
	@ResponseBody
	public JSONObject addCategory(HttpServletRequest request,
			HttpServletResponse response) {
		String parent_id;
		parent_id = request.getParameter("parent_id");
		if ("".equals(parent_id) || parent_id == null) {
			parent_id = categoryServiceI.queryId();
		}
		String categoryname = request.getParameter("categoryname");
		Map<String, Object> sort = new HashMap<String, Object>();
		JSONObject json = new JSONObject();
		sort.put("parent_id", parent_id);
		sort.put("category_name", categoryname);
		int insertAddSort = categoryServiceI.insertAddCategory(sort);
		if (insertAddSort > 0) {
			json.put("msg", "新增成功");
			json.put("status", "success");
		} else {
			logger.error("[请求课程分类信息异常!-ErrorMsg:]");
			json.put("status", "error");
			json.put("msg", "请求课程分类信息异常!");
		}
		return json;
	}

	/**
	 * @Title: editCategory
	 * @Description:(修改分类信息)
	 * @param @param request
	 * @param @param response
	 */
	@RequestMapping("/editCategory.bsh")
	@ResponseBody
	public JSONObject editCategory(HttpServletRequest request,
			HttpServletResponse response) {
		String id = request.getParameter("id");
		String categoryname = request.getParameter("categoryname");
		String parent_id = request.getParameter("parent_id");
		Map<String, Object> sort = new HashMap<String, Object>();
		JSONObject json = new JSONObject();
		sort.put("id", id);
		sort.put("parent_id", parent_id);
		sort.put("category_name", categoryname);
		int editSort = categoryServiceI.editCategory(sort);
		if (editSort > 0) {
			json.put("msg", "修改成功");
			json.put("status", "success");
		} else {
			logger.error("[请求课程分类信息异常-ErrorMsg:]");
			json.put("status", "error");
			json.put("msg", "请求课程分类信息异常!");
		}
		return json;
	}


	/**
	 * @Title: delCategory
	 * @Description:(删除分类信息)
	 * @param @param request
	 * @param @param response
	 */
	@RequestMapping("/delCategory.bsh")
	@ResponseBody
	public JSONObject delCategory(HttpServletRequest request,
			HttpServletResponse response) {
		String id = request.getParameter("id");
		JSONObject json = new JSONObject();
		List<Map<String, Object>> allCategory = categoryServiceI
				.getAllCategory();
		Map<String, String> t = new HashMap<String, String>();
		for (Map<String, Object> map : allCategory) {
			t.put(map.get("id").toString(), map.get("parent").toString());
		}
		System.out.println(JSON.toJSONString(t));
		 int number = removeTreeNodes(t, id);
			if (number > 0) {
				json.put("msg", "删除成功！");
				json.put("status","success");
			} else {
				logger.error("[请求课程分类信息异常-ErrorMsg:]");
				json.put("status", "error");
				json.put("msg", "请求课程分类信息异常!");
			}
		return json;
	}

	/**
	 * @Title: ischeck
	 * @Description:(检查是否重名分类名称)
	 * @param @param request
	 * @param @param response
	 */
	@RequestMapping("/ischeck.bsh")
	@ResponseBody
	public JSONObject ischeck(HttpServletRequest request,
			HttpServletResponse response) {
		String categoryname = request.getParameter("categoryname");
		Map<String, Object> sort = new HashMap<String, Object>();
		JSONObject json = new JSONObject();
		sort.put("category_name", categoryname);
		int ischeck = categoryServiceI.ischeck(sort);
		if (ischeck > 0) {
			json.put("msg", "该分类名称已被占用！");
			json.put("status", "success");
		} else {
			logger.error("[请求课程分类信息异常-ErrorMsg:]");
			json.put("status", "error");
			json.put("msg", "请求课程分类信息异常!");
		}

		return json;
	}

	@RequestMapping("/getcategoryinfo.bsh")
	public String getcategoryinfo(HttpServletRequest request,
			HttpServletResponse response) {
		return "baseData/systemManage/category/category.ftl";

	}

	/**
	 * @Description: (分类信息的服务层)
	 */
	@Resource
	private CategoryServiceI categoryServiceI;

	//级联删除树节点
	public int removeTreeNodes(Map<String, String> t, String k) {
		// 所有需要删除的子节点
		List<String> sons = new ArrayList<String>();
		sons.add(k);
		Integer numb = categoryServiceI.delCategory(k);
		List<String> temp = new ArrayList<String>();
		// 循环递归删除，所有以k为父节点的节点
		while (true) {
			for (String s : sons) {
				Set<String> keys = t.keySet();
				Iterator<String> it = keys.iterator();
				while (it.hasNext()) {
					String n = it.next();
					if (t.get(n).equals(s)) {
						temp.add(n);
						categoryServiceI.delCategory(n);
						it.remove();
					}
				}
			}

			if (temp.size() > 0) {
				sons = temp;
				temp = new CopyOnWriteArrayList<String>();
			} else {
				break;
			}
		}

		return numb;
	}
	
	
	
}
